package com.revenant.driver.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.apkfuns.logutils.LogUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.revenant.driver.App;
import com.revenant.driver.base.SplashActivity;
import com.revenant.driver.bean.BaseBean.MessageEvent;
import com.revenant.driver.ui.activity.LoginTokenActivity;

import java.io.IOException;
import java.nio.charset.Charset;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static com.revenant.driver.bean.BaseBean.MyEventCode.Token_LOGIN_SIGAL;
import static com.revenant.driver.utils.Constants.Name_header_token;


public class TokenHeadeInterceptor implements Interceptor {
    private List<String> netListUrl = Arrays.asList(
            "userLogin",
            "register",
            "sendSms",
            "mobileLogin",
            "outLogin",
            "forgetPass",
            "checkVersion",
            "selectEmptyCarList",
            "getAll",
            "file/upload",
            "findInfomasterList"
    );

    private boolean isneturl;
//    private boolean issetnetPas=true;
    private static AESHelper aes = AESHelper.getInstance();
    private Context context;
//    private static final AES aes = new AES(Mode.CTS, Padding.PKCS5Padding, "0CoJUm6Qyw8W8jud".getBytes(), "0102030405060708".getBytes());

    public TokenHeadeInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
//        for (int i = 0; i < netListUrl.size(); i++) {
//            if (request.url().toString().contains(netListUrl.get(i))) {
//                isneturl = true;
//                break;
//            }
//        }
//        LogUtils.d("判断"+isneturl+"url"+request.url());
//        Response response = chain.proceed(request);
        Request.Builder newBuilder = request.newBuilder();
        if (SPUtils.getUserToken(App.getApplication()).isEmpty()) {

            newBuilder.removeHeader("sign");
            newBuilder.removeHeader("X-Token");
            newBuilder.removeHeader("timestamp");
        } else {
            String timestamp = String.valueOf(DateUtil.current(false));//
            newBuilder.addHeader("sign", SecureUtil.md5(SecureUtil.md5(SecureUtil.md5(timestamp) + timestamp) + timestamp));
            newBuilder.addHeader("X-Token", SPUtils.getUserToken(App.getApplication()));
            newBuilder.addHeader(Name_header_token, String.valueOf(DateUtil.current(false)));

            newBuilder.addHeader("timestamp", timestamp);
        }

        Response responseheader = chain.proceed(newBuilder.build());

        ResponseBody responseBody = responseheader.body();
        if (responseBody != null && responseheader.code() == 200) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            String bodyString = buffer.clone().readString(charset);
            String urltoken;
            /*部分添加加密*/
//            if (isneturl) {
//                urltoken = bodyString;
//            } else {
//
//                urltoken = decryptStr(bodyString);
//            }

            /*全部加密*/
            isneturl=false;
            for (int i = 0; i < netListUrl.size(); i++) {
                if (request.url().toString().contains(netListUrl.get(i))) {
                    isneturl = true;
                    break;
                }
            }
            LogUtils.d("判断加密数据" + bodyString);
            if (bodyString.startsWith("{")){
                urltoken = bodyString;
            }else {
                urltoken = decryptStr(bodyString);
            }
//            if (isneturl&&!bodyString.startsWith("{")) {
//                urltoken = bodyString;
//            } else {
//                urltoken = decryptStr(bodyString);
//            }
            LogUtils.d("判断解密数据" + urltoken);
//            urltoken = decryptStr(bodyString);
            ResponseBody responseBodyjiemi = ResponseBody.create(contentType, urltoken);
            responseheader = responseheader.newBuilder().body(responseBodyjiemi).build();
            if (urltoken.contains("code")&&!urltoken.contains("success")) {
                String[] split = urltoken.split(",");
                String[] split1 = split[0].split(":");
                String replaceAll = split1[1].replaceAll("\"", "");
                Integer statuscode = Integer.valueOf(replaceAll);
                if (statuscode == 20 ||
                        statuscode == 21 ||
                        statuscode == 24 ||
                        statuscode == 25
                ) {
//                    LogUtils.d("拦截器code:" + statuscode + " url:" + request.url());
                    ToastUtils.showShort("当前账号已在另一台手机登录,此客户端已退出登录。如非本人操作请及时修改密码");
                    SPUtils.clearUserToken(App.getApplication());
                    SPUtils.clearAccounId(App.getApplication());
                    SPUtils.clearUsermobile(App.getApplication());
                    SPUtils.clearJpRidToken(App.getApplication());
                    AppUtils.relaunchApp();
//                    if (SPUtils.getHeaderToken(context) == 1) {
//                        MessageEvent event = new MessageEvent(Token_LOGIN_SIGAL);
//                        EventBusUtil.sendEvent(event);
//                        SPUtils.setHeaderToken(context,2);
//                    }
//                    Intent intent = new Intent();
//                    intent.setClass(context, SplashActivity.class);
//                    intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(intent);

//                ActivityUtils.removeAllActivity();


//                ActivityUtils.removeAllActivity();
//                OkGo.getInstance().cancelAll();

//                System.exit(0);
//                Intent intent=new Intent();
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setClass(context, SplashActivity.class);
//                context.startActivity(intent);
//                ActivityUtils.removeAllActivity();
                }
            }
        }
        return responseheader;
    }

//    public static String decryptStr(String content) {
//        return aes.decryptStr(content, Charset.forName("UTF-8"));
//    }

    public static String decryptStr(String content) {
        AESHelper aesDes = AESHelper.getInstance();
        String baseDecode = cn.hutool.core.codec.Base64.decodeStr(content);
        return aesDes.decrypt(baseDecode);

    }

    public static String encryStr(String content) {
        AESHelper aes = AESHelper.getInstance("YvllFaIri5Q6dxeG","sZM5JhqvbkprWA0u");
        String encrypt = aes.encrypt(content);
        return encrypt;

    }




}